/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.pms.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.expert.domain.Expert;
import com.fzhucc.modules.expert.repository.ExpertRepository;
import com.fzhucc.modules.fenRecordLog.service.FenRecordLogService;
import com.fzhucc.modules.lesson.domain.dto.LessonQueryCriteria;
import com.fzhucc.modules.pms.domain.Project;
import com.fzhucc.modules.pms.domain.ProjectNotice;
import com.fzhucc.modules.pms.domain.ProjectScore;
import com.fzhucc.modules.pms.domain.ProjectSmall;
import com.fzhucc.modules.pms.domain.dto.*;
import com.fzhucc.modules.pms.repository.ProjectRepository;
import com.fzhucc.modules.pms.repository.ProjectScoreRepository;
import com.fzhucc.modules.pms.repository.ProjectSmallRepository;
import com.fzhucc.modules.pms.service.mapstruct.ProjectNoticeMapper;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.thinktank.domain.Academician;
import com.fzhucc.modules.thinktank.domain.Capital;
import com.fzhucc.modules.thinktank.domain.Company;
import com.fzhucc.modules.thinktank.domain.Leader;
import com.fzhucc.modules.thinktank.repository.AcademicianRepository;
import com.fzhucc.modules.thinktank.repository.CapitalRepository;
import com.fzhucc.modules.thinktank.repository.CompanyRepository;
import com.fzhucc.modules.thinktank.repository.LeaderRepository;
import com.fzhucc.utils.PageUtil;
import com.fzhucc.utils.QueryHelp;
import com.fzhucc.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2022-11-23
 **/
@Service
@RequiredArgsConstructor
public class ProjectSmallService {

    private final ProjectSmallRepository projectSmallRepository;

    private final UserRepository userRepository;

    private final FenRecordLogService fenRecordLogService;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Value("${fen.type.xm}")
    public String xm;

    public Map<String,Object> queryAll(ProjectQueryCriteria criteria, Pageable pageable){
        Page<ProjectSmall> map = projectSmallRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(map);
    }

    //根据不同设置不同的部门查看 处理  福建省;  或者  福建省;福州市;   或者 福建省;福州市;马尾区; 这种类型
    public String setCriteria(ProjectQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            } else {
                return orgArea;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null  && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//包含福建省 则查全部
                return null;
            } else {
                if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return null;
                }
                if (res.getOrgArea().contains(";")) {
                    String[] split = res.getOrgArea().split(";");
                    if (split.length == 2) {
                        return split[1];
                    } else if (split.length == 3) {
                        return split[2];
                    } else if (split.length == 1) {
                        return split[0];
                    } else {
                        throw new BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw new BadRequestException("用户ID未找到");
        }
    }


    public Map<String,Object> queryAllXcx(ProjectQueryCriteria criteria, Pageable pageable){
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(xm);
        } catch (Exception e) {

        }

        String area = "";
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                area = null;
            }else{
                area = criteria.getOrgArea();
            }
        }else{
            area = setCriteria(criteria);
        }

        String text = criteria.getText();
        if (text == null || text.equals("")){
            if (criteria.getLevel() == null){//查全部
                if (area == null){
                    Page<ProjectSmall> map = projectSmallRepository.findAllXcxWithOutLikeTextWithOutLevelWithOutOrgArea(pageable);
                    return PageUtil.toPage(map);
                }else{
                    Page<ProjectSmall> map = projectSmallRepository.findAllXcxWithOutLikeTextWithOutLevel(area,pageable);
                    return PageUtil.toPage(map);
                }
            }else{
                if (area == null){
                    Page<ProjectSmall> map = projectSmallRepository.findAllXcxWithOutLikeTextWithOutOrgArea(criteria.getLevel(),pageable);
                    return PageUtil.toPage(map);
                }else{
                    Page<ProjectSmall> map = projectSmallRepository.findAllXcxWithOutLikeText(criteria.getLevel(),area,pageable);
                    return PageUtil.toPage(map);
                }
            }
        }else{
            if (criteria.getLevel() == null){//查全部
                if (area == null){
                    String res = "%" + text + "%";
                    Page<ProjectSmall> map = projectSmallRepository.findAllXcxWithOutLevelWithOutOrgArea(res,pageable);
                    return PageUtil.toPage(map);
                }else{
                    String res = "%" + text + "%";
                    Page<ProjectSmall> map = projectSmallRepository.findAllXcxWithOutLevel(res,area,pageable);
                    return PageUtil.toPage(map);
                }
            }else{
                if (area == null){
                    String res = "%" + text + "%";
                    Page<ProjectSmall> map = projectSmallRepository.findAllXcxWithOutAreaOrg(criteria.getLevel(),res,pageable);
                    return PageUtil.toPage(map);
                }else{
                    String res = "%" + text + "%";
                    Page<ProjectSmall> map = projectSmallRepository.findAllXcx(criteria.getLevel(),res,area,pageable);
                    return PageUtil.toPage(map);
                }
            }
        }
    }

}